package com.ggkt.common.utils;
import com.ggkt.common.utils.exception.ExceptionUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Date Utility Class used to convert Strings to Dates and Timestamps
 */
public class DateUtil {

	private static Log log = LogFactory.getLog(DateUtil.class);
	
	public static DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	public static String FORMAT_SHORT = "yyyyMM";
	public static final String FORMAT_FULL = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_MIDDLE = "yyyy-MM-dd";
	public static final String DAY_BEGIN = " 00:00:00";
	public static final String DAY_END = " 23:59:59";
	public static DateTimeFormatter DATE_FORMAT_SHORT = DateTimeFormatter.ofPattern(FORMAT_SHORT);

	public static LocalDate toLocalDate(Date date) {
		
		return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
	}


	public static LocalDate formatMiddleLocalDate(String date) {
		return toLocalDate(formatMiddleDate(date));
	}


	public static Date formatMiddleDate(String date) {
		return DateUtil.stringToDate(date, FORMAT_MIDDLE);
	}

	public static Date toDay(LocalDate date) {
		
		return stringToDate(date.format(dayFormatter), "yyyy-MM-dd");
	}

	/**
	 * 返回自从（格林威治时间 1970 年 1 月 1 日 00:00:00）到当前时间的秒数。
	 */
	public static int time() {
		return (int) (new Date().getTime() / 1000);
	}

	/**
	 * 返回自从（格林威治时间 1970 年 1 月 1 日 00:00:00）到任意时间的秒数。
	 */
	public static int time(Date date) {

		return (int) (date.getTime() / 1000);
	}

	/**
	 * 将指定时间返回秒数
	 */
	public static int time(String str) {
		Date d = stringToDate(str, "yyyy-MM-dd HH:mm:ss");
		return (int) (d.getTime() / 1000);
	}

	public static long getTime() {
		Date date = new Date();
		return date.getTime() / 1000;
	}

	/**
	 * 将秒数转换成当前时间 string
	 */
	public static String getDateByTime(long time, String format) {
		SimpleDateFormat ft = new SimpleDateFormat(format);
		return ft.format(new Date((long) time * 1000));
	}

	// 当前时间转到时间stirng
	public static String getNowToString(String format) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String sNowTime = sdf.format(date);
		return sNowTime;

	}

	// 当前时间转到时间Date
	public static Date getNowToDate(String format) {
		String date = getNowToString("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Date sNowTime = sdf.parse(date);
			return sNowTime;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(ExceptionUtil.getEMsg(e));
			return null;
		}
	}

	// 当前时间转到时间Date
	public static Date getNowDate(Date date, String format) {
		String dateStr = getNowDateString(date, "yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			Date sNowTime = sdf.parse(dateStr);
			return sNowTime;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(ExceptionUtil.getEMsg(e));
			return null;
		}
	}

	// date转到时间stirng
	public static String getNowDateString(Date date, String format) {
		if (date != null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			String sNowTime = sdf.format(date);
			return sNowTime;
		} else {
			return null;
		}

	}

	public static String getDateString(Date date) {
		return getNowDateString(date,"yyyy-MM-dd HH:mm:ss");

	}

	public static String getDateAddDay(int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calender = Calendar.getInstance();
		calender.add(Calendar.DATE, num);
		return sdf.format(calender.getTime());
	}

	/**
	 * @Description: 将日期转化为 yyyyMMdd 格式
	 * @Author: xuhuibin
	 * @Date: 2021/5/29 9:22
	 */
	public static String getDateStr (Date date) {
		return getNowDateString(date,"yyyyMMdd");
	}

	/**
	 * @Description: 按yyyyMMddHHmmss格式返回今天的日期
	 * @Author: xuhuibin
	 * @Date: 2021/6/4 17:40
	 */
	public static String getToday() {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = new Date();
		String today = formatter.format(date);
		return today;
	}

	/**
	 * @Description: 将日期转化为 yyyy-MM-dd 格式
	 * @Author: xuhuibin
	 * @Date: 2021/5/29 9:22
	 */
	public static String getDateStr2 (Date date) {
		return getNowDateString(date,"yyyy-MM-dd");
	}

	/**
	 * @Description: 将日期转化为 yyyyMMdd 格式
	 * @Author: xuhuibin
	 * @Date: 2021/5/29 9:22
	 */
	public static String getDateStr3 (Date date) {
		return getNowDateString(date,"yyyy-MM-dd hh:mm:ss");
	}

	/**
	 * @Description: 获取当天之后的时间 天
	 * @Author: xuhuibin
	 * @Date: 2021/5/29 9:23
	 */
	public static Date afterNowTime(int days) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE,days);
		return calendar.getTime();
	}

	// 时间stirng转到date
	public static Date stringToDate(String str, String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			if (str != null && !str.equals("")) {
				date = sdf.parse(str);
			}
		} catch (ParseException e) {
			log.error("stringToDate error, message: " + e.getMessage() + ", str: " + str + ", format: " + format);
		}

		return date;
	}

	// 获取系统当前月份，返回数字
	public static Integer getMonth() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.MONTH) + 1;
	}

	// 获取系统当前年份，返回数字
	public static Integer getYear() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.YEAR);
	}

	// 获取今天是当前年份的第几天，返回数字
	public static Integer getDayOfYear() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.DAY_OF_YEAR);
	}

	// 获取今天是当前年份的第几天，返回数字
	public static Integer getDayOfMonth() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.DAY_OF_MONTH);
	}

	// 得到几个小时前的时间
	public static String getBeforeHour(Integer num) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - num);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(calendar.getTime());
	}

	/**
	 * 返回00:00:00
	 *
	 * @param date
	 */
	public static Date getStartDayTime(Date date) {
		if (date != null) {
			String s = getNowDateString(date, "yyyy-MM-dd");
			return stringToDate(s + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
		} else {
			return null;
		}
	}

	/**
	 * 返回23:59:59
	 *
	 * @param date
	 */
	public static Date getEndDayTime(Date date) {
		if (date != null) {
			String s = getNowDateString(date, "yyyy-MM-dd");
			return stringToDate(s + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
		} else {
			return null;
		}
	}

	/**
	 * 获取第二天信息
	 *
	 * @param endDate
	 */
	public static Date getNextDay(Date endDate) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endDate);
		calendar.add(Calendar.DAY_OF_MONTH, 1);
		return calendar.getTime();
	}

	/**
	 * 获取前后N天
	 *
	 * @param n
	 * @param endDate
	 */
	public static Date getNextNDay(Date endDate, int n) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endDate);
		calendar.add(Calendar.DAY_OF_MONTH, n);
		return calendar.getTime();
	}

	/**
	 * 获取前一天信息
	 *
	 * @param endDate
	 */
	public static Date getYestoday(Date endDate) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(endDate);
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		return calendar.getTime();
	}

	/**
	 * 上一周的开始日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getPrevWeekBeginDay(int startDay) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(getCurrentWeekBeginDay(startDay));
		calendar.add(Calendar.DATE, -7);
		return calendar.getTime();
	}

	/**
	 * 上一周的结束日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getPrevWeekEndDay(int startDay) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(getCurrentWeekBeginDay(startDay));
		calendar.add(Calendar.DATE, -1);
		return calendar.getTime();
	}

	/**
	 * 指定日期所在周的开始日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getWeekBeginDay(Date date, int startDay) {

		Date dayDate = getNowDate(date, "yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dayDate);

		int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (day == 0) {
			day = 7;
		}

		int offset = 0;
		if (startDay <= day) {
			offset = startDay - day;
		} else {
			offset = startDay - day - 7;
		}
		calendar.add(Calendar.DATE, offset);

		return calendar.getTime();
	}

	/**
	 * 指定日期所在周的结束日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getWeekEndDay(Date date, int startDay) {

		Date dayDate = getNowDate(date, "yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dayDate);

		int day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
		if (day == 0) {
			day = 7;
		}

		int offset = 0;
		if (startDay <= day) {
			offset = 6 - (day - startDay);
		} else {
			offset = startDay - day - 1;
		}
		calendar.add(Calendar.DATE, offset);

		return calendar.getTime();
	}

	/**
	 * 当前周的开始日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getCurrentWeekBeginDay(int startDay) {

		return getWeekBeginDay(new Date(), startDay);
	}

	/**
	 * 当前周的结束日期
	 *
	 * @param startDay 1 --7，标识星期从周几为第一条
	 */
	public static Date getCurrentWeekEndDay(int startDay) {

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(getCurrentWeekBeginDay(startDay));
		calendar.add(Calendar.DATE, 6);
		return calendar.getTime();
	}

	/**
	 * 当前月的开始日期
	 */
	public static Date getCurrentMonthBeginDay() {

		Date now = getNowToDate("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		calendar.set(Calendar.DATE, 1);

		return calendar.getTime();
	}

	/**
	 * 指定日期所在月的结束日期
	 */
	public static Date getMonthEndDay(Date date) {

		Date dayDate = getNowDate(date, "yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(dayDate);
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DATE, 1);
		calendar.add(Calendar.DATE, -1);

		return calendar.getTime();
	}

	/**
	 * 当前月的结束日期
	 */
	public static Date getCurrentMonthEndDay() {

		Date now = getNowToDate("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DATE, 1);
		calendar.add(Calendar.DATE, -1);

		return calendar.getTime();
	}

	/**
	 * 上一个月的开始日期
	 */
	public static Date getPrevMonthBeginDay() {

		Date now = getNowToDate("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		calendar.add(Calendar.MONTH, -1);
		calendar.set(Calendar.DATE, 1);

		return calendar.getTime();
	}

	/**
	 * 上一个月的结束日期
	 */
	public static Date getPrevMonthEndDay() {

		Date now = getNowToDate("yyyy-MM-dd");

		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		calendar.set(Calendar.DATE, 1);
		calendar.add(Calendar.DATE, -1);

		return calendar.getTime();
	}

	/**
	 * 指定日期{@code date}间隔几天{@code offset}的新日期
	 *
	 * @param date
	 * @param offset
	 * @return
	 */
	public static Date offsetday(Date date, int offset) {
		return new Date(date.getTime() + offset * 24 * 60 * 60 * 1000);
	}

	/**
	 * 返回两个日期的时间差，毫秒
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static Long getDiffDate(Date date1, Date date2) {
		if (date1 != null && date2 != null) {
			return date1.getTime() - date2.getTime();
		} else {
			return null;
		}
	}

	/**
	 * 返回两个日期的间隔的天数，可以为负数
	 * 
	 * @param date1
	 */
	public static int getDayNum(Date date1, Date date2) {

		Long diff = getDiffDate(date1, date2);
		if (diff == null) {
			return 0;
		}
		return (int) (diff / 86400000);
	}

	/**
	 * 返回两个日期的间隔的天数，可以为负数
	 * 
	 * @param startstr endstr
	 */
	public static int getDayNum(String startstr, String endstr) {
		String format = "yyyy-MM-dd";

		Date start = stringToDate(startstr, format);
		Date end = stringToDate(endstr, format);

		Long diff = getDiffDate(end, start);
		if (diff == null) {
			return 0;
		}
		return (int) (diff / 86400000);
	}

	/**
	 * 获取前几个月日期
	 *
	 * @param date   指定日期
	 * @param months 前几个月
	 * @return
	 */
	public static Date getPrevMonth(Date date, int months) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, -months);
		return calendar.getTime();
	}

	/**
	 * getHour(获取当前小时数)
	 *
	 * @return Integer
	 */
	public static Integer getHour() {
		Calendar calendar = Calendar.getInstance();
		return calendar.get(Calendar.HOUR_OF_DAY);
	}

	public static String formatSeconds(long seconds) {

		if (seconds == 0) {
			return "0";
		} else {

			long minute = seconds / 60;
			if (minute <= 0) {

				return seconds + "秒";
			} else {

				long hour = minute / 60;
				if (hour <= 0) {

					return minute + "分钟";
				} else {
					long day = hour / 24;
					if (day <= 0) {

						return hour + "小时" + minute % 60 + "分钟";
					} else {
						long year = day / 365;

						if (year <= 0) {

							return day + "天" + hour % 24 + "小时";
						} else {

							return year + "年" + day % 365 + "天";
						}

					}

				}

			}

		}

	}

	/**
	 * 判断是否是当前年
	 *
	 * @param date 指定日期
	 * @return
	 */
	public static boolean isCurrentYear(Date date) {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy");
		String s1 = sf.format(date);
		String s2 = sf.format(new Date());
		if (s1.equals(s2)) {
			return true;
		} else {
			return false;
		}
	}

	public static long mktime(long year0, long mon0, long day, long hour, long min, long sec) {
		long mon = mon0, year = year0;
		if (0 > (mon -= 2)) {
			mon += 12;
			year -= 1;
		}
		return (long) ((((year / 4 - year / 100 + year / 400 + 367 * mon / 12 + day) + year * 365 - 719499) * 24 + hour)
				* 60 + min) * 60 + sec;
	}

	// 返回当前时间到第二天凌晨的秒数
	public static long getSecondToEnd() {
		Date date1 = new Date();
		Date date2 = getStartDayTime(getNextDay(new Date()));
		return getDiffDate(date2, date1) / 1000;
	}

	public static String getTimeFormat(Date time) {
		String retFormat = "";
		if (time != null) {
			long diff = new Date().getTime() - time.getTime();
			if (diff < 60000) {// 1分钟内
				retFormat = "刚刚";
			} else if (diff < 3600000) {// 一小时内
				retFormat = diff / 60000 + "分钟前";
			} else if (diff < 86400000) {// 一天内
				retFormat = diff / 3600000 + "小时前";
			} else if (diff < 2592000000L) {// 一月内
				retFormat = diff / 86400000 + "天前";
			} else if (diff < 31104000000L) {// 一年内
				retFormat = diff / 2592000000L + "月前";
			} else {
				retFormat = diff / 31104000000L + "年前";
			}
		}
		return retFormat;
	}

	//返回相差的天数，可为负数
	public static long getDiffNumTwo(Date start, Date end){
		long quot = 0;
		quot = end.getTime() - start.getTime();
		quot = quot / 1000;
		return quot;
	}

	public static void main(String[] args) {

		  Date d = stringToDate("2016-11-10 14:13:52","yyyy-MM-dd HH:mm:ss");

		  Integer a = DateUtil.time(); Integer c = DateUtil.time(d);

		  System.out.println(a-c);



	}

	public static Long getDiffDate(String addTime, String preTime) {
		// TODO Auto-generated method stub
		String format = "yyyy-MM-dd HH:mm:ss";
		Date addTimeDate = stringToDate(addTime, format);
		Date preTimeDate = stringToDate(preTime, format);

		return DateUtil.getDiffDate(addTimeDate, preTimeDate);
	}

	/**
	 * getIntegerExpireToDate(int类型秒数转为日期格式字符串)
	 *
	 * @param addtime
	 * @return String
	 */
	public static String getIntegerExpireToDate(Integer addtime) {
		String str = addtime + "";
		Long time = Long.parseLong(str);
		;
		Date d = new Date(time * 1000);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(d);
	}

	/**
	 * 计算出与指定时间papaDay n天之后的时间
	 *
	 * @return
	 * @throws ParseException
	 */
	public static String getAddDateDay(Date papaDay, int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(papaDay);
			calender.add(Calendar.DATE, num);
			return sdf.format(calender.getTime());
		} catch (Exception e) {
			return null;
		}
	}

	// 当前时间转到时间Date
	public static Date parseNowToDate(String format) {
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date sNowTime = ft.parse(format);
			return sNowTime;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 计算出与指定时间papaDay n月之后的时间
	 *
	 * @return
	 * @throws ParseException
	 */
	public static String getAddMonth(String papaDay, int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(sdf.parse(papaDay));
			calender.add(Calendar.MONTH, num);
			return sdf.format(calender.getTime());
		} catch (ParseException e) {
			return null;
		}
	}

	public static long getDiffNumBySec(Date start){
		long quot = 0;
		Date d_end = new Date();
		quot = d_end.getTime() - start.getTime();
		quot = quot / 1000 ;
		return Math.abs(quot);
	}
	public static long getDiffNumBySec(String start,Date end){
		long quot = 0;
		SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date d_start = ft.parse( start );
			Date d_end =  end ;
			quot = d_end.getTime() - d_start.getTime();
			quot = quot / 1000 ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return Math.abs(quot);
	}

	/**
	 * 根据给定的日期获取改月的第一天或者最后一天
	 * @author zxs
	 * @param theday 格式为 2009-01-03
	 * @param type 1 返回当月第一天 2 返回当月最后一天
	 * @return
	 */
	public static String getDayOfMonth(String theday,int type){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calender = Calendar.getInstance();
		if (type < 1 || type > 2 ) {
			return null;
		}
		try {
			calender.setTime(sdf.parse(theday));
			calender.set(Calendar.DATE, 1);
			if (type == 2) {
				calender.roll(Calendar.DATE, -1);
			}
			return sdf.format(calender.getTime());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取起始日期补位
	 * @return
	 * @throws ParseException
	 */
	public static Date addStrDateStart(String str) {
		if (str != null && str != "") {
			String timeStr = str+" 00:00:00";
			Date date = stringToDate(timeStr,"yyyy-MM-dd HH:mm:ss");
			return date;
		}else{
			return null;
		}
	}

	/**
	 * 获取末尾日期补位
	 * @return
	 * @throws ParseException
	 */
	public static Date addStrDateEnd(String str) {
		if (str != null && str != "") {
			String timeStr = str+" 23:59:59";
			Date date = stringToDate(timeStr,"yyyy-MM-dd HH:mm:ss");
			return date;
		}else{
			return null;
		}
	}

	/**
	 * 计算出与指定时间papaDay n秒之后的时间
	 * @return
	 * @throws ParseException
	 */
	public static String getAddSecond(String papaDay, int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(sdf.parse(papaDay));
			calender.add(Calendar.SECOND, num);
			return sdf.format(calender.getTime());
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 计算出与指定时间papaDay n天之后的时间
	 * @return yyyy-MM-dd
	 * @throws ParseException
	 */
	public static String getAddDay(String papaDay, int num) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(sdf.parse(papaDay));
			calender.add(Calendar.DATE, num);
			return sdf.format(calender.getTime());
		} catch (ParseException e) {
			return null;
		}
	}

}
